<?php
namespace app\user\controller;
use think\Cache;
use think\Controller;
use think\Db;
use think\Request;
use think\Session;
use \think\Validate;

class Login extends Controller {
	public function login() {
		return $this->fetch('login/login');
	}

	public function reg() {
		
		return $this->fetch('login/reg');
	}

	public function doreg() {
		/*添加用户*/
		$user=$_POST["user_name"];
		$pwd=$_POST["password"];
		$pwd=sha1(md5($pwd));
		$res=Db::name("user")->insert(['user_name'=>$user,'password'=>$pwd,'status'=>1]);
		return json(['code' => 1, 'msg' => '注册成功']);
	}

	public function dologin(Request $request) {

		$user_name = $request->post('user_name/s');
		$password = $request->post('password/s');

		if (empty($user_name) || empty($password)) {
			return json(['code' => 0, 'msg' => '账号或密码未填写']);
		}

		// 验证
		$validate = new Validate([
			'user_name|用户名' => 'require|alphaDash',
			'password|密码' => 'require|alphaDash',
		]);
		$param = [
			'user_name' => $user_name,
			'password' => $password,
		];
		if (!$validate->check($param)) {
			return json(['code' => 0, 'msg' => $validate->getError()]);
		}
		$users = Db::name('user')->where('user_name', $user_name)->find();

		if (empty($users)) {
			return json(['code' => 0, 'msg' => '账号或密码错误1']);
		}
		if ($users['user_name'] == $user_name && $users['password'] == sha1(md5($password))) {
			if ($users['status'] == 1) {
				
				// $token = admin_token();
				// unset($users['password']);
				// $users['token'] = $token;
				 Session::set('user_name', $users);
				// // 更新token
				// @Db::name('admin')
				// 	->where('id', $users['id'])
				// 	->update(['token' => $token]);

				return json(['code' => 1, 'msg' => '登录成功']);
			} else {
				return json(['code' => 0, 'msg' => '账户被封禁,请联系管理员!']);
			}
		} else {
			return json(['code' => 0, 'msg' => '账号或密码错误2']);
		}

	}

	public function outlogin() {
		Session::delete('user_name');
		return $this->redirect('/user/login.html');
	}

}